<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }

        h1 {
            width: 100%;
            height: 100px;
            background-color: skyblue;
            display: flex;
            justify-content: center;
            align-items: center;
            position: relative;
        }

        h1 > p{
            position: absolute;
            font-size: 20px;
            top: 50%;
            right: 50px;
            transform: translateY(-50%);
            display: none;
        }

        h1 > p.active {
            display: block;
        }

        h1 > p > span{
            color: red;
        }
    </style>
</head>
<body>
    <h1>
        首页
        <p class="off"><a href="./login.html">您好,请登录</a></p>
        <p class="on">您好,<span>杨璐</span></p>
    </h1>

    <script>
        // 获取元素  
        const offBox = document.querySelector('.off');
        const onBox = document.querySelector('.on');


       

        //从本地存储中获取数据
        // id  token 
        const id = window.localStorage.getItem('id');
        const token = window.localStorage.getItem('token');
        // console.log(id,token);
        test();
        //判断是否有id和token
        function test(){
            if(!id || !token){
                // 如果到了这里 说明没有登录过 
                // 隐藏onBox 显示offBox
                offBox.classList.add('active');
                onBox.classList.remove('active');
                return
            }
        }

        // 到了这里说明 登录过 
        const xhr = new XMLHttpRequest();

        xhr.open('GET',`http://localhost:8888/users/info?id=${id}`);

        // 拿到个人信息 

        xhr.onload = function(){
            const res = JSON.parse(xhr.responseText);
            console.log(res)

            if(res.code === 401){
                onBox.classList.remove('active');
                offBox.classList.add('active');
                return 
            }
            onBox.firstElementChild.innerText = res.info.nickname;
            
                onBox.classList.add('active');
                offBox.classList.remove('active');
        }
        xhr.setRequestHeader('authorization',token)
        xhr.send()

    </script>
</body>
</html>